/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ui;

import chart.BarChart;
import chart.LineChart;
import data_access.DataAccess;
import data_access.ResultObj;

import java.awt.Color;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;

import javax.swing.JOptionPane;
import javax.swing.SortOrder;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.decorator.ColorHighlighter;
import org.jdesktop.swingx.decorator.HighlightPredicate;
import org.jdesktop.swingx.decorator.Highlighter;
import org.jdesktop.swingx.decorator.HighlighterFactory;

/**
 * 
 * @author Anh
 */
public class Chart extends javax.swing.JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Screen screen;

	/**
	 * Creates new form Chart
	 */
	public Chart() {
		initComponents();
		initData(tableData);
	}

	public Chart(Screen screen) {
		initComponents();
		initData(tableData);
		this.screen = screen;
	}

	private void initData(JXTable table) {
		try {

			String[] s = { "Id", "DataName", "TestingSize", "ClassNumber", "AccuracyOAO", "TimeOAO", "AccuracyDDAG",
					"TimeDDAG", "AccuracyADAG", "TimeADAG", "Date" };
			Vector<String> vColumn = new Vector<String>();
			Vector<Vector<String>> vData = new Vector<Vector<String>>();
			DataAccess da = new DataAccess();
			ResultSet rs = da.getData("result");
			ResultSetMetaData rsmt = rs.getMetaData();
			for (int i = 0; i < rsmt.getColumnCount(); i++) {
				vColumn.addElement(s[i]);
			}
			table.setModel(new DefaultTableModel(vColumn, 0));

			while (rs.next()) {
				Vector<String> vRow = new Vector<String>();
				for (int i = 1; i <= rsmt.getColumnCount(); i++) {
					vRow.addElement(rs.getString(i));
				}

				vData.add(vRow);
				table.setModel(new DefaultTableModel(vData, vColumn));
			}

			table.setSortOrder(0, SortOrder.DESCENDING);
			table.setEditable(false);
			table.setHorizontalScrollEnabled(true);
			table.setColumnControlVisible(false);
			Highlighter hl = HighlighterFactory.createSimpleStriping(new Color(215, 215, 215));
			table.setHighlighters(hl);
			table.addHighlighter(new ColorHighlighter(HighlightPredicate.ROLLOVER_ROW, null, Color.BLUE));
			table.setAutoResizeMode(JXTable.AUTO_RESIZE_ALL_COLUMNS);
			da.closeConnect();
		} catch (Exception ex) {
			JOptionPane.showMessageDialog(null, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Form Editor.
	 */

	// <editor-fold defaultstate="collapsed"
	// desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jPanel1 = new javax.swing.JPanel();
		jScrollPane1 = new javax.swing.JScrollPane();
		tableData = new org.jdesktop.swingx.JXTable();
		btnViewChart = new javax.swing.JButton();

		setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		setTitle("History");
		setIconImage(new javax.swing.ImageIcon(getClass().getResource("/Resources/java.png")).getImage());
		addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosed(java.awt.event.WindowEvent evt) {
				formWindowClosed(evt);
			}
		});

		jPanel1.setBackground(new java.awt.Color(255, 255, 204));
		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Result"));

		tableData.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

		}, new String[] {

		}));
		tableData.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				tableDataMouseClicked(evt);
			}
		});
		jScrollPane1.setViewportView(tableData);

		btnViewChart.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/chart.png"))); // NOI18N
		btnViewChart.setText("ViewChart");
		btnViewChart.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				btnViewChartActionPerformed(evt);
			}
		});

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						jPanel1Layout
								.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										jPanel1Layout
												.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jScrollPane1)
												.addGroup(
														javax.swing.GroupLayout.Alignment.TRAILING,
														jPanel1Layout.createSequentialGroup()
																.addGap(0, 598, Short.MAX_VALUE)
																.addComponent(btnViewChart))).addContainerGap()));
		jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						jPanel1Layout.createSequentialGroup().addContainerGap()
								.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addComponent(btnViewChart).addContainerGap()));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap()));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
				layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
								javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addContainerGap()));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void btnViewChartActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_btnViewChartActionPerformed
		ArrayList<ResultObj> resultList = new ArrayList<>();
		for (int i = 0; i < tableData.getSelectedRows().length; i++) {
			ResultObj rsObj = new ResultObj(tableData.getValueAt(tableData.getSelectedRows()[i], 1).toString(),
					Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 2).toString()),
					Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 3).toString()),
					Double.parseDouble(tableData.getValueAt(tableData.getSelectedRows()[i], 4).toString()),
					Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 5).toString()),
					Double.parseDouble(tableData.getValueAt(tableData.getSelectedRows()[i], 6).toString()),
					Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 7).toString()),
					Double.parseDouble(tableData.getValueAt(tableData.getSelectedRows()[i], 8).toString()),
					Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 9).toString()));
			resultList.add(rsObj);
		}

		Collections.sort(resultList, new Comparator<ResultObj>() {

			@Override
			public int compare(ResultObj arg0, ResultObj arg1) {
				// sort by classnumber
				int sort = arg0.getClassNumber() > arg1.getClassNumber() ? 1 : (arg0.getClassNumber() < arg1
						.getClassNumber() ? -1 : 0);
				// sort by testingsize
				if (sort == 0) {
					sort = arg0.getTestingSize() > arg1.getTestingSize() ? 1 : (arg0.getTestingSize() < arg1
							.getTestingSize() ? -1 : 0);
				}

				return sort;
			}
		});

		if (resultList.size() == 1) {
			BarChart barChart = new BarChart(resultList.get(0));
			barChart.pack();
			barChart.setVisible(true);
		} else if (resultList.size() > 1) {
			LineChart lineChart = new LineChart(resultList);
			lineChart.pack();
			lineChart.setVisible(true);
		} else {
			JOptionPane.showMessageDialog(this, "Choose data first!", "Error", JOptionPane.ERROR_MESSAGE);
		}
	}// GEN-LAST:event_btnViewChartActionPerformed

	private void tableDataMouseClicked(java.awt.event.MouseEvent evt) {// GEN-FIRST:event_tableDataMouseClicked
		if (SwingUtilities.isRightMouseButton(evt)) {
			if (tableData.getSelectedRows().length > 0) {
				if (JOptionPane.showConfirmDialog(this, "Do you want to delete data?", "Confirm",
						JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
					try {
						DataAccess da = new DataAccess();
						for (int i = 0; i < tableData.getSelectedRows().length; i++) {
							ResultObj rsObj = new ResultObj();
							rsObj.setId(Integer.parseInt(tableData.getValueAt(tableData.getSelectedRows()[i], 0)
									.toString()));
							da.deleteData(rsObj);
						}
						AbstractTableModel model = (AbstractTableModel) tableData.getModel();
						model.fireTableDataChanged();
						initData(tableData);

						JOptionPane.showMessageDialog(this, "Delete Success!", "Success",
								JOptionPane.INFORMATION_MESSAGE);
					} catch (Exception e) {
						JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
					}
				}
			} else {
				JOptionPane
						.showMessageDialog(this, "Choose data to delete!", "Notice", JOptionPane.INFORMATION_MESSAGE);
			}
		}
	}// GEN-LAST:event_tableDataMouseClicked

	private void formWindowClosed(java.awt.event.WindowEvent evt) {// GEN-FIRST:event_formWindowClosed
		this.screen.setEnabled(true);
		this.screen.setAutoRequestFocus(true);
	}// GEN-LAST:event_formWindowClosed

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		/* Set the Nimbus look and feel */
		// <editor-fold defaultstate="collapsed"
		// desc=" Look and feel setting code (optional) ">
		/*
		 * If Nimbus (introduced in Java SE 6) is not available, stay with the
		 * default look and feel. For details see
		 * http://download.oracle.com/javase
		 * /tutorial/uiswing/lookandfeel/plaf.html
		 */
		try {
			for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
				if ("Nimbus".equals(info.getName())) {
					javax.swing.UIManager.setLookAndFeel(info.getClassName());
					break;
				}
			}
		} catch (ClassNotFoundException ex) {
			java.util.logging.Logger.getLogger(Chart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (InstantiationException ex) {
			java.util.logging.Logger.getLogger(Chart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (IllegalAccessException ex) {
			java.util.logging.Logger.getLogger(Chart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		} catch (javax.swing.UnsupportedLookAndFeelException ex) {
			java.util.logging.Logger.getLogger(Chart.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
		}
		// </editor-fold>

		/* Create and display the form */
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Chart().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton btnViewChart;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	public org.jdesktop.swingx.JXTable tableData;
	// End of variables declaration//GEN-END:variables
}
